#include "transfile.h"

int copy_string(const char *source,char *dest){
    while ((*dest++ = *source++) != '\0');
    return 0;
}

int init_train(trans_train_t *train){
    train->type=0;
    train->length=0;
    bzero(train->contxt,sizeof(train->contxt));
    return 0 ;
}

int trans_file(int sockfd,char *path,char *filename){
    struct stat file_stat;
    int ret=stat(path,&file_stat);
    int file_length=file_stat.st_size;
    //get length of file

    trans_train_t train;
    init_train(&train);
    int fd=open(path,O_RDONLY);
    //ready to sent file

    char fn[100]={0};

    copy_string(filename,fn);
    train.type=1;
    train.length=strlen(fn);
    memcpy(&train.contxt,fn,strlen(fn));
    send(sockfd,&train,sizeof(train.type)+sizeof(train.length)+train.length,0);
    //sent file name

    if(file_length>large_file){//large file sent
        sendfile(sockfd,fd,NULL,file_length);
    }
    else{//tiny file sent
        while(1){
            init_train(&train);
            ssize_t rd_num=read(fd,&train.contxt,sizeof(train.contxt));
            train.type=2;
            train.length=rd_num;
            send(sockfd,&train,sizeof(train.type)+sizeof(train.length)+train.length,0);
            if(rd_num==0){//文件读为0,文件已经结束
                close(fd);
                break;
            }
        }
    }
    return 0;
}

int check_hash(){
    return 0;
}

